<template>
  <view class="settle-container">
    <!-- 全选 -->
    <label class="radio" @click="clickAllHandler">
      <radio :checked="isChecked" color="#ff0000" /><text>全选</text>
    </label>
    <!-- 合计 -->
    <view class="am-box">
      合计:<text class="amount">￥{{checkedOverallPrice}}</text>
    </view>
    <!-- 结算 -->
    <view class="settle-btn" @click="settlement">
      结算({{checkedCount}})
    </view>
  </view>
</template>

<script>
  import {
    mapGetters,
    mapState,
    mapMutations
  } from 'vuex'
  import {
    showMsg
  } from '../../utils/interact/index.js'
  import {
    escook
  } from '@/utils/escook/index.js'
  export default {
    name: "settle",
    computed: {
      ...mapGetters('m_cart', ['checkedCount', 'checkedOverallPrice']),
      ...mapState('m_cart', ['isChecked', 'cart']),
      ...mapState('m_user', ['token', 'address']),
    },
    data() {
      return {
        seconds: 3,
        timer: null,
      };
    },
    methods: {
      ...mapMutations('m_cart', ['saveIsChecked', 'clickAllRadio']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      clickAllHandler() {
        /* 
          假设现在购物车中三个商品处于勾选，还有4个没勾选，点击全选框时，未勾选的4个商品处于勾选，全选按钮处于勾选，
          再次点击全选框，所有商品处于未勾选，全选框处于未勾选
         */
        this.clickAllRadio();
      },
      settlement() {
        //处理三种非法情况：
        /* 
        未登录，未勾选任何商品，未选择收获地址
        */
        //未登录
        if (!this.token) return this.delayNavLogin();;

        //未勾选任何商品
        if (!this.checkedCount) return showMsg('请勾选要结算的商品');
        this.address === {}
        //未选择收获地址
        if (!this.address.userName) return showMsg('请选择收货地址');

        //所有条件满足后，实现支付功能
        /* 
        1.创建订单，服务器返回订单编号
        2. 拿着1得到订单编号访问预支付接口，其返回一个预支付对象
        3. 拿着预支付对象访问uni-app提供的支付接口
        */
        this.payOrder(); //1
      },

      //展示倒计时提示框
      showTips(seconds) {
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算，' + seconds + '秒后自动跳转到登录页面',
          mask: true,
          duration: 1500,
        })
      },

      //倒计时跳转到登录页面
      delayNavLogin() {
        const that = this;
        this.seconds = 3;
        this.showTips(this.seconds);

        //每隔一秒执行一次
        this.timer = setInterval(() => {
          this.seconds--;
          if (this.seconds <= 0) {
            //关闭倒计时
            clearInterval(this.timer);

            //跳转到登录页
            uni.switchTab({
              url: '/pages/profile/profile',
              success() {
                //成功跳转后将重定向信息保存在vuex
                that.updateRedirectInfo({
                  openType: 'switchTab',
                  from: '/pages/cart/cart',
                })
              }
            });

            return
          }
          this.showTips(this.seconds);
        }, 1000);

      },

      //支付功能
      async payOrder() {
        //1. 创建订单
        //1.1  组织访问创建订单接口需要的参数
        const order = {
          // order_price:this.checkedOverallPrice,
          order_price: 0.01,
          consignee_addr: this.address,
          goods: this.cart.filter(c => c.goods_state).map(goods => {
            return {
              goods_number: goods.goods_count,
              goods_id: goods.goods_id,
              goods_price: goods.goods_price
            };
          }),
        }

        //1.2  携带参数访问接口
        const {
          data: payRes
        } = await escook.post('api/public/v1/my/orders/create', order);
        if (payRes.meta.status !== 200) return showMsg('订单创建失败');


        //1.3  服务器返回订单编号goods_number
        const goods_number = payRes.message.goods_number;
        this.previewPay(goods_number); //2
      },
      //获取预支付参数
      async previewPay(goods_number) {
        const {
          data: prePay
        } = await escook.post('api/public/v1/my/orders/req_unifiedorder', {
          order_number: goods_number
        });
        if (prePay.meta.status !== 200) return showMsg('获取预支付参数失败');
        prePay.message.pay.appId = 'wxb0569d6270a39b8e';
        const prePayObj = prePay.message.pay;
        this.createPay(prePayObj, goods_number); //3
      },

      //访问uni.requestPayment()
      createPay(payObj, order_number) {
        uni.requestPayment({
          ...prePayObj,
          success: async () => {
            const {
              data: res
            } = await escook.post('api/public/v1/my/orders/chkOrder', {
              order_number
            });
            if (res.meta.status !== 200) return showMsg('订单未支付');
            uni.showToast({
              icon: 'success',
              title: '支付成功',
            })
          },
          fail: () => {
            showMsg('取消支付');
          }
        })
      },
    },
  }
</script>

<style lang="scss">
  .settle-container {
    width: 100%;
    position: fixed;
    bottom: 0%;
    left: 0;
    z-index: 99;
    display: flex;
    height: 50px;
    align-items: center;
    justify-content: space-between;
    background-color: #efefef;
    font-size: 14px;
    padding-left: 5px;

    // 全选
    .radio {}

    // 合计
    .am-box {
      .amount {
        color: #c00;
        font-weight: bold;
      }
    }

    //结算
    .settle-btn {
      background-color: #c00;
      height: 100%;
      min-width: 90px;
      line-height: 50px;
      text-align: center;
      color: white;
    }
  }
</style>